package medical_application;
/** CSIS 343 Group 2 Course Project
 *  @authors Agnes Oliveira, Liane Heidemann, Daniel Schraufnagel, Matthew Lee
 */
import java.io.*;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import java.util.*;
import javax.swing.JOptionPane;

/**
 *  Read_Write_XML class with methods for reading, writing, and translating our XML data.
 */
public class Read_Write_XML {
	/* All the variables necessary for building our Vectors and XML documents */
	final String directory= "src/medical_application/";
	final String patientFilename = "patient.xml";
	final String patientFullPath = directory + patientFilename;
	File patientInfile = new File(patientFullPath);
	Document patientIndoc = null;
	XPath path = XPathFactory.newInstance().newXPath();
	final String patientCount = "count(/Patients/Patient)";
	static Vector<Patient> patientVector= new Vector<Patient>();

	
	/**
	 * Reads an XML file of Patients and parses that data into a document object.
	 * @param there exists an XML file for reading.
	 * @return a Document object.
	 */
	protected Document readPatientXML(){
		try {
			DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			patientIndoc = docbuilder.parse( patientInfile );
			patientIndoc.getDocumentElement().normalize();
		} catch (ParserConfigurationException e) {
			JOptionPane.showMessageDialog(null, "Not able to create DocumentBuilder object!", "E R R O R", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		} catch (SAXException e) {
			JOptionPane.showMessageDialog(null, "Not able to read XML file: " + patientFullPath, "E R R O R", JOptionPane.ERROR_MESSAGE );
			e.printStackTrace();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Not able to open file: " + patientFullPath, "E R R O R", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}
		 return patientIndoc;
	}//end of readPatientXML()
	
	/**
	 * Writes a document object(XML data) and returns a Vector of Patient objects.
	 * @param there exists a valid document object.
	 * @returns nothing, but fills a Vector array with Patient objects.
	 */
	protected void createPatientVector(){
		if (patientIndoc != null && path != null){
			try {
				int n = Integer.parseInt(path.evaluate(patientCount, patientIndoc));//n = total amount of Patients
			for(int i = 1; i < n + 1; i++){	
				String fName = path.evaluate("/Patients/Patient[" + i + "]/Name/First", patientIndoc);
				String mName = path.evaluate("/Patients/Patient[" + i + "]/Name/Middle", patientIndoc);
				String lName = path.evaluate("/Patients/Patient[" + i + "]/Name/Last", patientIndoc);
			    String age = path.evaluate("/Patients/Patient[" + i + "]/Age", patientIndoc);
			    String dob = path.evaluate("/Patients/Patient[" + i + "]/DOB", patientIndoc);    	
			    String phone = path.evaluate("/Patients/Patient[" + i + "]/Phone", patientIndoc);
				String address = path.evaluate("/Patients/Patient[" + i + "]/Address", patientIndoc);
				String allergies = path.evaluate("/Patients/Patient[" + i + "]/Allergies", patientIndoc);
				String scripts = path.evaluate("/Patients/Patient[" + i + "]/Scripts", patientIndoc);
				String insure = path.evaluate("/Patients/Patient[" + i + "]/Insurance", patientIndoc);
				Patient temp = new Patient(fName, mName, lName, address, insure, allergies, scripts, dob, age, phone);
				patientVector.add(temp);
			}
			} catch (NumberFormatException e) {
				JOptionPane.showMessageDialog(null, "Not able to read number.", "E R R O R", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			} catch (XPathExpressionException e) {
				JOptionPane.showMessageDialog(null, "Bad XPath expression.", "E R R O R", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}
		} else {
			 System.err.println("Cannot inspect document!");
		}
	}//end of writeVector()
	
	/**
	 * writeXML function write from the Patient records to an XML file
	 * @param a vector of patient records to iterate
	 * @return a saved xml file in the programs package
	 */
	protected void writePatientXML(){
		try {
	        BufferedWriter out = new BufferedWriter(new FileWriter(patientFullPath));
	        out.write("<?xml version=" + "\"1.0\"" + "?>\n");
	        out.write("<Patients>\n");
	        for (int i = 0; i < patientVector.size(); i++) {
	          out.write("  <Patient>\n");
	          out.write("    <Name>\n");
	          out.write("      <First>" + patientVector.elementAt(i).getFirst() + "</First>\n");
	          out.write("      <Middle>" + patientVector.elementAt(i).getMiddle() + "</Middle>\n");
	          out.write("      <Last>" + patientVector.elementAt(i).getLast() + "</Last>\n");
	          out.write("    </Name>\n");
	          out.write("    <Age>" + patientVector.elementAt(i).getAge() + "</Age>\n");
	          out.write("    <DOB>" + patientVector.elementAt(i).getDOB() + "</DOB>\n");
	          out.write("    <Phone>" + patientVector.elementAt(i).getPhone() + "</Phone>\n");
	          out.write("    <Address>" + patientVector.elementAt(i).getAddress() + "</Address>\n");
	          out.write("    <Allergies>" + patientVector.elementAt(i).getAllergies() + "</Allergies>\n");
	          out.write("    <Scripts>" + patientVector.elementAt(i).getScripts() + "</Scripts>\n");
	          out.write("    <Insurance>" + patientVector.elementAt(i).getInsurance() + "</Insurance>\n");
	          out.write("  </Patient>\n");
	        }
	        out.write("</Patients>");
	        out.close();
	        } catch (IOException e) {
	        	JOptionPane.showMessageDialog(null, "Unable to save XML file", "E R R O R", JOptionPane.ERROR_MESSAGE);
	        	e.printStackTrace();
	        }
	}//end of writeXML()
}//end of class

